package com.zjy.financialsystemjavafx.controller;

import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.PieChart;
import javafx.scene.chart.XYChart;
import javafx.fxml.FXMLLoader;
import javafx.scene.layout.BorderPane;
import javafx.scene.Parent;
import java.io.IOException;
import com.zjy.financialsystemjavafx.service.DashboardService;
import java.time.YearMonth;
import java.util.Map;
import com.zjy.financialsystemjavafx.util.SessionContext;

/**
 * 仪表盘界面控制器
 */
public class DashboardController {

    @FXML
    private BorderPane rootPane;

    @FXML
    private Button accountBtn;

    @FXML
    private Button transactionBtn;

    @FXML
    private Button loanBtn;

    @FXML
    private Button reportBtn;

    @FXML
    private Button settingsBtn;

    @FXML
    private Label totalAssetLabel;

    @FXML
    private LineChart<String, Number> monthlyTrendChart;

    @FXML
    private PieChart categoryPieChart;

    @FXML
    private PieChart accountPieChart;

    @FXML
    private PieChart loanPieChart;

    /**
     * 初始化方法
     */
    @FXML
    private void initialize() {
        DashboardService service = new DashboardService();
        int userId = SessionContext.getCurrentUser().getUserId();
        try {
            // 总资产
            double totalAssets = service.getTotalAssets(userId);
            totalAssetLabel.setText("¥" + String.format("%.2f", totalAssets));

            // 月度收支趋势（近6个月）
            YearMonth endMonth = YearMonth.now();
            YearMonth startMonth = endMonth.minusMonths(5);
            Map<YearMonth, Double> incMap = service.getMonthlyAmount(userId, startMonth, endMonth, "Income");
            Map<YearMonth, Double> expMap = service.getMonthlyAmount(userId, startMonth, endMonth, "Expense");
            XYChart.Series<String, Number> incomeSeries = new XYChart.Series<>();
            incomeSeries.setName("收入");
            XYChart.Series<String, Number> expenseSeries = new XYChart.Series<>();
            expenseSeries.setName("支出");
            for (YearMonth ym : incMap.keySet()) {
                String label = String.format("%02d月", ym.getMonthValue());
                incomeSeries.getData().add(new XYChart.Data<>(label, incMap.get(ym)));
                expenseSeries.getData().add(new XYChart.Data<>(label, expMap.get(ym)));
            }
            monthlyTrendChart.getData().clear();
            monthlyTrendChart.getData().addAll(incomeSeries, expenseSeries);

            // 收支分类占比（支出）
            Map<String, Double> catMap = service.getExpenseByCategory(userId);
            categoryPieChart.getData().clear();
            catMap.forEach((k, v) -> categoryPieChart.getData().add(new PieChart.Data(k, v)));

            // 账户余额分布
            Map<String, Double> accMap = service.getAccountDistribution(userId);
            accountPieChart.getData().clear();
            accMap.forEach((k, v) -> accountPieChart.getData().add(new PieChart.Data(k, v)));

            // 借贷概览
            Map<String, Double> loanMap = service.getLoanOverview(userId);
            loanPieChart.getData().clear();
            loanMap.forEach((k, v) -> loanPieChart.getData().add(new PieChart.Data(k, v)));

        } catch (Exception e) {
            e.printStackTrace();
            Alert alert = new Alert(AlertType.ERROR);
            alert.setTitle("数据加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载仪表盘数据: " + e.getMessage());
            alert.showAndWait();
        }
    }

    @FXML
    private void handleAccount(ActionEvent event) {
        try {
            Parent pane = FXMLLoader.load(getClass().getResource("/com/zjy/financialsystemjavafx/view/AccountManagement.fxml"));
            rootPane.setCenter(pane);
        } catch (IOException e) {
            e.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载账户管理界面");
            alert.showAndWait();
        }
    }

    @FXML
    private void handleTransaction(ActionEvent event) {
        try {
            Parent pane = FXMLLoader.load(getClass().getResource("/com/zjy/financialsystemjavafx/view/TransactionManagement.fxml"));
            rootPane.setCenter(pane);
        } catch (IOException e) {
            e.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载收支管理界面");
            alert.showAndWait();
        }
    }

    @FXML
    private void handleLoan(ActionEvent event) {
        try {
            Parent pane = FXMLLoader.load(getClass().getResource("/com/zjy/financialsystemjavafx/view/LoanManagement.fxml"));
            rootPane.setCenter(pane);
        } catch (IOException e) {
            e.printStackTrace();
            Alert alert = new Alert(AlertType.ERROR);
            alert.setTitle("加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载借贷管理界面");
            alert.showAndWait();
        }
    }

    @FXML
    private void handleReport(ActionEvent event) {
        try {
            Parent pane = FXMLLoader.load(getClass().getResource("/com/zjy/financialsystemjavafx/view/ReportView.fxml"));
            rootPane.setCenter(pane);
        } catch (IOException e) {
            e.printStackTrace();
            Alert alert = new Alert(AlertType.ERROR);
            alert.setTitle("加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载报表统计界面");
            alert.showAndWait();
        }
    }

    @FXML
    private void handleSettings(ActionEvent event) {
        try {
            Parent pane = FXMLLoader.load(getClass().getResource("/com/zjy/financialsystemjavafx/view/SettingsView.fxml"));
            rootPane.setCenter(pane);
        } catch (IOException e) {
            e.printStackTrace();
            Alert alert = new Alert(AlertType.ERROR);
            alert.setTitle("加载错误");
            alert.setHeaderText(null);
            alert.setContentText("无法加载设置界面");
            alert.showAndWait();
        }
    }
} 